import { useState, useEffect } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { Save, X, Calendar, Tag, FileText, Layout } from 'lucide-react';
import { RichTextEditor } from '../components/RichTextEditor';
import { TagInput } from '../components/TagInput';
import TemplateSelector from '../components/TemplateSelector';
import TemplateEditor from '../components/TemplateEditor';
import { useDiaryStore } from '../store/diaryStore';
import { DiaryTemplate } from '../types/templates';
import { format } from 'date-fns';
import { toast } from 'sonner';

const moods = [
  { value: 'happy', label: '😊 Happy', emoji: '😊' },
  { value: 'sad', label: '😢 Sad', emoji: '😢' },
  { value: 'excited', label: '🤩 Excited', emoji: '🤩' },
  { value: 'calm', label: '😌 Calm', emoji: '😌' },
  { value: 'anxious', label: '😰 Anxious', emoji: '😰' },
  { value: 'grateful', label: '🙏 Grateful', emoji: '🙏' },
  { value: 'thoughtful', label: '🤔 Thoughtful', emoji: '🤔' },
  { value: 'energetic', label: '⚡ Energetic', emoji: '⚡' },
];

export default function WriteEntry() {
  const navigate = useNavigate();
  const { id } = useParams();
  const { addEntry, updateEntry, getEntryById, selectedTemplate, setSelectedTemplate, getTemplateById, incrementTemplateUsage } = useDiaryStore();
  
  // Check if we're editing an existing entry
  const existingEntry = id ? getEntryById(id) : null;
  const isEditing = !!existingEntry;
  
  const [title, setTitle] = useState(existingEntry?.title || '');
  const [content, setContent] = useState(existingEntry?.content || '');
  const [selectedMood, setSelectedMood] = useState(existingEntry?.mood || '');
  const [tags, setTags] = useState(existingEntry?.tags || []);
  const [selectedDate, setSelectedDate] = useState(
    existingEntry?.date || format(new Date(), 'yyyy-MM-dd')
  );
  const [isSaving, setIsSaving] = useState(false);
  const [writingMode, setWritingMode] = useState<'template' | 'freeform'>('freeform');
  const [currentTemplate, setCurrentTemplate] = useState<DiaryTemplate | null>(null);
  const [templateSections, setTemplateSections] = useState<{ [sectionId: string]: string }>({});
  const [showTemplateSelector, setShowTemplateSelector] = useState(false);
  
  // Initialize template data for existing entries
  useEffect(() => {
    if (existingEntry?.templateId) {
      const template = getTemplateById(existingEntry.templateId);
      if (template) {
        setCurrentTemplate(template);
        setWritingMode('template');
        setTemplateSections(existingEntry.templateSections || {});
      }
    }
  }, [existingEntry, getTemplateById]);
  
  const handleSave = async () => {
    // Validate content based on writing mode
    if (writingMode === 'template' && currentTemplate) {
      const requiredSections = currentTemplate.sections.filter(s => s.required);
      const missingRequired = requiredSections.filter(s => !templateSections[s.id]?.trim());
      
      if (missingRequired.length > 0) {
        toast.error(`Please complete all required sections: ${missingRequired.map(s => s.title).join(', ')}`);
        return;
      }
    } else if (!content.trim()) {
      toast.error('Please write something before saving!');
      return;
    }
    
    setIsSaving(true);
    
    try {
      const baseEntryData = {
        title: title.trim() || (currentTemplate ? `${currentTemplate.name} Entry` : 'Untitled Entry'),
        content: content.trim(),
        date: selectedDate,
        mood: selectedMood,
        tags: [...tags, ...(currentTemplate?.defaultTags || [])].filter((tag, index, arr) => arr.indexOf(tag) === index),
      };
      
      // Add template-specific data if using a template
      const entryData = writingMode === 'template' && currentTemplate
        ? {
            ...baseEntryData,
            templateId: currentTemplate.id,
            templateSections,
          }
        : baseEntryData;
      
      if (isEditing && id) {
        updateEntry(id, entryData);
        toast.success('Entry updated successfully!');
      } else {
        addEntry(entryData);
        toast.success('Entry saved successfully!');
        
        // Increment template usage if using a template
        if (currentTemplate) {
          incrementTemplateUsage(currentTemplate.id);
        }
      }
      
      navigate('/');
    } catch (error) {
      toast.error('Failed to save entry. Please try again.');
    } finally {
      setIsSaving(false);
    }
  };
  
  const handleCancel = () => {
    const hasChanges = content.trim() || title.trim() || Object.values(templateSections).some(v => v.trim());
    if (hasChanges) {
      if (window.confirm('You have unsaved changes. Are you sure you want to leave?')) {
        navigate(-1);
      }
    } else {
      navigate(-1);
    }
  };
  
  const handleTemplateSelect = (template: DiaryTemplate | null) => {
    if (template) {
      setCurrentTemplate(template);
      setWritingMode('template');
      setTemplateSections({});
      setContent('');
      // Add template's default tags
      const newTags = [...tags, ...template.defaultTags].filter((tag, index, arr) => arr.indexOf(tag) === index);
      setTags(newTags);
    } else {
      setCurrentTemplate(null);
      setWritingMode('freeform');
      setTemplateSections({});
    }
    setShowTemplateSelector(false);
  };
  
  const handleModeSwitch = (mode: 'template' | 'freeform') => {
    if (mode === 'template') {
      setShowTemplateSelector(true);
    } else {
      setWritingMode('freeform');
      setCurrentTemplate(null);
      setTemplateSections({});
    }
  };
  
  const wordCount = content.replace(/<[^>]*>/g, '').split(/\s+/).filter(word => word.length > 0).length;

  return (
    <div className="max-w-4xl mx-auto">
      {/* Header */}
      <div className="flex items-center justify-between mb-8">
        <div>
          <h1 className="text-2xl font-inter font-bold text-forest-green">
            {isEditing ? 'Edit Entry' : 'Write New Entry'}
          </h1>
          <p className="text-warm-gray mt-1">
            {isEditing ? 'Update your thoughts' : 'Capture your thoughts and feelings'}
          </p>
        </div>
        
        <div className="flex gap-3">
          <button
            onClick={handleCancel}
            className="flex items-center gap-2 px-4 py-2 text-warm-gray border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors"
          >
            <X size={16} />
            Cancel
          </button>
          
          <button
            onClick={handleSave}
            disabled={isSaving || (writingMode === 'freeform' ? !content.trim() : (writingMode === 'template' && currentTemplate ? currentTemplate.sections.filter(s => s.required).some(s => !templateSections[s.id]?.trim()) : false))}
            className="btn-primary flex items-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed"
          >
            <Save size={16} />
            {isSaving ? 'Saving...' : 'Save Entry'}
          </button>
        </div>
      </div>
      
      {/* Writing Mode Selection */}
      <div className="card mb-6">
        <div className="flex items-center justify-between mb-4">
          <h3 className="text-lg font-medium text-forest-green">Writing Mode</h3>
          
          <div className="flex bg-gray-100 rounded-lg p-1">
            <button
              onClick={() => handleModeSwitch('freeform')}
              className={`flex items-center gap-2 px-4 py-2 rounded-md text-sm font-medium transition-colors ${
                writingMode === 'freeform'
                  ? 'bg-white text-forest-green shadow-sm'
                  : 'text-warm-gray hover:text-forest-green'
              }`}
            >
              <FileText className="w-4 h-4" />
              Free Writing
            </button>
            
            <button
              onClick={() => handleModeSwitch('template')}
              className={`flex items-center gap-2 px-4 py-2 rounded-md text-sm font-medium transition-colors ${
                writingMode === 'template'
                  ? 'bg-white text-forest-green shadow-sm'
                  : 'text-warm-gray hover:text-forest-green'
              }`}
            >
              <Layout className="w-4 h-4" />
              Template
            </button>
          </div>
        </div>
        
        {writingMode === 'template' && currentTemplate && (
          <div className="flex items-center justify-between p-3 bg-blue-50 rounded-lg border border-blue-200">
            <div className="flex items-center gap-3">
              <div className="w-8 h-8 bg-blue-500 rounded-lg flex items-center justify-center">
                <span className="text-white text-sm font-medium">{currentTemplate.icon}</span>
              </div>
              <div>
                <p className="font-medium text-gray-900">{currentTemplate.name}</p>
                <p className="text-sm text-gray-600">{currentTemplate.description}</p>
              </div>
            </div>
            
            <button
              onClick={() => setShowTemplateSelector(true)}
              className="text-sm text-blue-600 hover:text-blue-700 font-medium"
            >
              Change Template
            </button>
          </div>
        )}
        
        {writingMode === 'freeform' && (
          <p className="text-sm text-warm-gray">
            Write freely without any structure. Perfect for stream-of-consciousness journaling.
          </p>
        )}
      </div>
      
      {/* Template Selector Modal */}
      {showTemplateSelector && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-lg max-w-4xl w-full max-h-[90vh] overflow-hidden">
            <div className="p-6 border-b border-gray-200">
              <div className="flex items-center justify-between">
                <h2 className="text-xl font-semibold text-gray-900">Choose a Template</h2>
                <button
                  onClick={() => setShowTemplateSelector(false)}
                  className="p-2 text-gray-400 hover:text-gray-600 transition-colors"
                >
                  <X className="w-5 h-5" />
                </button>
              </div>
            </div>
            
            <div className="p-6 overflow-y-auto max-h-[calc(90vh-120px)]">
              <TemplateSelector
              onSelect={handleTemplateSelect}
              onClose={() => setShowTemplateSelector(false)}
              selectedTemplate={currentTemplate}
            />
            </div>
          </div>
        </div>
      )}
      
      {/* Entry Form */}
      <div className="space-y-6">
        {/* Metadata Section */}
        <div className="card">
          <div className="grid grid-cols-1 md:grid-cols-3 gap-6 mb-6">
            {/* Title */}
            <div>
              <label className="block text-sm font-medium text-warm-gray mb-2">
                Title (Optional)
              </label>
              <input
                type="text"
                value={title}
                onChange={(e) => setTitle(e.target.value)}
                placeholder="Give your entry a title..."
                className="input-field"
              />
            </div>
            
            {/* Date */}
            <div>
              <label className="block text-sm font-medium text-warm-gray mb-2">
                <Calendar className="inline w-4 h-4 mr-1" />
                Date
              </label>
              <input
                type="date"
                value={selectedDate}
                onChange={(e) => setSelectedDate(e.target.value)}
                className="input-field"
              />
            </div>
            
            {/* Mood */}
            <div>
              <label className="block text-sm font-medium text-warm-gray mb-2">
                How are you feeling?
              </label>
              <select
                value={selectedMood}
                onChange={(e) => setSelectedMood(e.target.value)}
                className="input-field"
              >
                <option value="">Select mood...</option>
                {moods.map((mood) => (
                  <option key={mood.value} value={mood.value}>
                    {mood.label}
                  </option>
                ))}
              </select>
            </div>
          </div>
          
          {/* Tags Section */}
          <div>
            <label className="block text-sm font-medium text-warm-gray mb-2">
              <Tag className="inline w-4 h-4 mr-1" />
              Tags
            </label>
            <TagInput
              tags={tags}
              onChange={setTags}
              placeholder="Add tags to organize your entries..."
            />
            <p className="text-xs text-sage mt-2">
              Press Enter or comma to add tags. Click on suggested tags to add them quickly.
            </p>
          </div>
        </div>
        
        {/* Content Editor */}
        {writingMode === 'template' && currentTemplate ? (
          <div className="card">
            <TemplateEditor
              template={currentTemplate}
              initialSections={templateSections}
              onChange={setTemplateSections}
              onContentChange={setContent}
            />
          </div>
        ) : (
          <div className="card">
            <div className="mb-4">
              <label className="block text-sm font-medium text-warm-gray mb-2">
                Your thoughts
              </label>
            </div>
            
            <RichTextEditor
              content={content}
              onChange={setContent}
              placeholder="Start writing your thoughts... What's on your mind today?"
              className="min-h-[400px]"
            />
            
            {/* Word Count */}
            <div className="mt-4 text-right">
              <span className="text-sm text-sage">
                {wordCount} {wordCount === 1 ? 'word' : 'words'}
              </span>
            </div>
          </div>
        )}
        
        {/* Preview Selected Mood */}
        {selectedMood && (
          <div className="card">
            <div className="flex items-center gap-3">
              <span className="text-2xl">
                {moods.find(m => m.value === selectedMood)?.emoji}
              </span>
              <div>
                <p className="text-sm text-warm-gray">Current mood</p>
                <p className="font-medium text-forest-green">
                  {moods.find(m => m.value === selectedMood)?.label.replace(/^\S+\s/, '')}
                </p>
              </div>
            </div>
          </div>
        )}
      </div>
      
      {/* Auto-save indicator */}
      <div className="fixed bottom-6 right-6">
        <div className="bg-white rounded-lg shadow-lg px-4 py-2 border border-gray-200">
          <p className="text-xs text-warm-gray">
            💾 Changes are saved locally
          </p>
        </div>
      </div>
    </div>
  );
}